<script lang="jsx" setup>
import dayjs from 'dayjs';
import { nextTick, ref } from 'vue';
import { Button } from 'ant-design-vue';
import Table from '@/components/common/table.vue';
import CommonSearch from '@/components/common/common-search.vue';
import {
  addEvent,
  bindUser,
  deleteEvent,
  getUserSelectList,
  updateEvent,
  updateEventStatus
} from '@/service/api/modules/manage/event';
import Modal from '@/components/common/modal.vue';
import Edit from './modules/edit.vue';

const commonSearchRef = ref(null);
const tableRef = ref(null);
const searchParams = ref({
  keywords: null
});

const searchFormList = [
  {
    type: 'input',
    key: 'keywords',
    label: '事件名称',
    placeholder: '请输入事件名称',
    span: 24,
    md: 12,
    lg: 8,
    xl: 8,
    xxl: 6
  }
];

const column = [
  {
    key: 'dataIndex',
    dataIndex: 'dataIndex',
    title: '序号',
    width: 70,
    fixed: 'left',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'eventName',
    dataIndex: 'eventName',
    title: '事件名称',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'eventTypeName',
    dataIndex: 'eventTypeName',
    title: '事件类型',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'eventCode',
    dataIndex: 'eventCode',
    title: '事件编码',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 300
  },
  {
    key: 'eventStatusName',
    dataIndex: 'eventStatusName',
    title: '状态',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'remark',
    dataIndex: 'remark',
    title: '备注',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'userName',
    dataIndex: 'userName',
    title: '绑定人',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 200
  },
  {
    key: 'createBy',
    dataIndex: 'createBy',
    title: '创建人',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 180
  },
  {
    key: 'createTime',
    dataIndex: 'createTime',
    title: '创建时间',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 180,
    customRender: ({ record }) => {
      return dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss');
    }
  },
  {
    key: 'czRow',
    dataIndex: 'czRow',
    title: '操作',
    align: 'center',
    checked: true,
    ellipsis: true,
    width: 180,
    customRender: ({ record }) => {
      return (
        <div>
          <Button
            class="pl-3px pr-3px"
            type="link"
            danger
            v-hasAuth={[['manage:event:del']]}
            onClick={() => {
              delRow(record);
            }}
          >
            删除
          </Button>
          <Button
            type="link"
            class="pl-3px pr-3px"
            v-hasAuth={[['manage:event:update']]}
            onClick={() => {
              handleEdit(record);
            }}
          >
            修改
          </Button>
          <Button
            type="link"
            class="pl-3px pr-3px"
            v-hasAuth={[['manage:event:bind']]}
            onClick={() => {
              handleBindModalOpen(record);
            }}
          >
            绑定
          </Button>
          <Button
            type="link"
            class="pl-3px pr-3px"
            v-hasAuth={[['manage:event:changeStatus']]}
            onClick={() => {
              updateState(record);
            }}
          >
            {{ 1: '禁用', 2: '启用' }[record.eventStatus]}
          </Button>
        </div>
      );
    }
  }
];

function search() {
  tableRef.value.getData(1);
}

function reset() {
  nextTick(() => {
    searchParams.value = {
      keywords: null
    };
    search();
  });
}

const modalVisible = ref(false);
const modleEditLoading = ref(false);

function updateState(row) {
  window.$modal.confirm({
    title: `确定${row.eventStatus === 1 ? '禁用' : '启用'} "${row.eventName}" 吗?`,
    onOk: () => {
      updateEventStatus({
        eventNoticeId: row.eventNoticeUuid,
        eventStatus: row.eventStatus === 1 ? 2 : 1
      }).then(({ error }) => {
        if (!error) {
          window.$message.success(`${row.eventStatus === 1 ? '禁用' : '启用'}成功`);
          search();
        }
      });
    },
    onCancel: () => {}
  });
}

function delRow(row) {
  window.$modal.confirm({
    title: `确定删除"${row.eventName}"吗?`,
    onOk: () => {
      deleteEvent(row.eventNoticeUuid).then(({ error }) => {
        if (!error) {
          window.$message.success('删除成功');
          search();
        }
      });
    },
    onCancel: () => {}
  });
}

const currrentRow = ref(null);
const operateType = ref('add');
function handleEdit(row) {
  currrentRow.value = row;
  modalVisible.value = true;
  operateType.value = row ? 'edit' : 'add';
}

const editRef = ref(null);

function handleClose() {
  modalVisible.value = false;
  currrentRow.value = null;
}

function handleOk() {
  const editFormVal = { ...editRef.value.model };
  modleEditLoading.value = true;
  let pro;

  if (operateType.value === 'edit') {
    pro = updateEvent({
      ...currrentRow.value,
      ...editFormVal
    });
  } else {
    pro = addEvent({
      ...editFormVal
    });
  }

  pro
    .then(({ error }) => {
      if (!error) {
        window.$message.success(`${operateType.value === 'edit' ? '修改' : '新增'}成功`);
        handleClose();
        search();
      }
    })
    .finally(() => (modleEditLoading.value = false));
}

const bindVisible = ref(false);
const bindLoading = ref(false);
const userName = ref([]);
const userList = ref([]);

function getUserList() {
  // getUserSelectList().then(({ data, error }) => {
  //   if (!error) {
  //     userList.value = data.rows;
  //   }
  // });
  getUserSelectList().then( res => {
    let data = res.otherData
    userList.value = data.rows;
  });

}

getUserList();

const bindId = ref(null);
function handleBindModalOpen(row) {
  bindVisible.value = true;
  bindId.value = row.eventNoticeUuid;
  userName.value = row.userIdArr || [];
}

function handleBindClose() {
  bindVisible.value = false;
  bindId.value = null;
  userName.value = [];
}

const filterOption = (input, option) => {
  return option.label.includes(input);
};

function handleBindOk() {
  bindLoading.value = true;
  const data = {
    userList: userName.value,
    eventNoticeId: bindId.value
  };
  bindUser(data)
    .then(({ error }) => {
      if (!error) {
        window.$message.success('绑定成功');
        handleBindClose();
        search();
      }
    })
    .finally(() => (bindLoading.value = false));
}
</script>

<template>
  <div class="message jl-main-page min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <CommonSearch
      ref="commonSearchRef"
      v-model:searchParams="searchParams"
      :form-list="searchFormList"
      :is-search="true"
      @search="search"
      @reset="reset"
    ></CommonSearch>

    <Table
      ref="tableRef"
      v-model:searchParams="searchParams"
      :column="column"
      :show-row-selection="false"
      row-key="tableUuid"
      :scroll="{ y: 'auto' }"
      is-init-get-data
      url="/qms/agv/notice/eventnotice/list"
      :auto-generate-uuid="true"
    >
      <template #tableTitle>
        <AButton
          v-hasAuth="['manage:event:add']"
          type="primary"
          size="small"
          ghost
          class="mini-btn mr-8px"
          @click="handleEdit(null)"
        >
          <template #icon>
            <icon-ic-round-add class="align-sub text-icon" />
          </template>
          <span class="ml-3px">新增</span>
        </AButton>
      </template>
    </Table>

    <Modal
      v-model:visible="modalVisible"
      :title="`${operateType === 'add' ? '新增' : '修改'}事件信息`"
      width="700px"
      height="400px"
      :centered="true"
      :destroy-on-close="true"
      @close="handleClose"
    >
      <!-- <Recover></Recover> -->
      <Edit ref="editRef" :row-data="currrentRow"></Edit>
      <template #footer>
        <div class="modal-footer">
          <AButton type="primary" :loading="modleEditLoading" @click="handleOk">保 存</AButton>
          <AButton @click="handleClose">关 闭</AButton>
        </div>
      </template>
    </Modal>

    <Modal
      v-model:visible="bindVisible"
      title="绑定事件信息"
      width="600px"
      height="200px"
      :destroy-on-close="true"
      @close="handleBindClose"
    >
      <div class="bind-modal-content">
        <AForm :model="model" :label-col="{ lg: 8, xs: 4 }" label-wrap>
          <AFormItem label="收件人" name="userName" :label-col="{}">
            <ASelect
              v-model:value="userName"
              placeholder="请选择收件人"
              show-search
              :filter-option="filterOption"
              mode="multiple"
              :max-tag-count="5"
            >
              <ASelectOption v-for="item in userList" :key="item.userId" :label="item.nickName" :value="item.userId">
                {{ item.nickName }}
              </ASelectOption>
            </ASelect>
          </AFormItem>
        </AForm>
      </div>
      <template #footer>
        <div class="modal-footer">
          <AButton type="primary" :loading="bindLoading" @click="handleBindOk">提 交</AButton>
          <AButton @click="handleBindClose">关 闭</AButton>
        </div>
      </template>
    </Modal>
  </div>
</template>
